package com.ubhave.powertracker;

import java.util.Calendar;
import java.util.Date;

import com.ubhave.powertracker.R;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class DailyViewReminderNotification extends Service{

	SharedPreferences settings;
	SharedPreferences.Editor editor;
	LifeGuideConnector lgc;
	String usr;
	String intervention;
	
	PageSensorLogger psl;
	PageLogger pl;
	
	boolean inhibited;
	String[] inhibitedWeeks;
	int week;
	int day;
	Date currentDate;
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker: ", "Alarm test 3");
		return null;
	}
	
	@Override
    public void onCreate() {
		
		settings =PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		editor = settings.edit();
        lgc = new LifeGuideConnector(settings);
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
		
		if(settings.getBoolean("SensorsOn", false))
			psl = new PageSensorLogger(this);
		pl=new PageLogger(this);
		
		class AsyncLog extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Log
				/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
				editor.commit();
		        if(!usr.equals("")&&!intervention.equals(""))
		        	lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
		        else
		        	Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
				try{
					pl.makeLog();
				
		        	//Sensor Log
		        	if(settings.getBoolean("SensorsOn", false)){
		    			psl.makeLog();
		        	}
				} catch (PowerTrackerInvalidAuthKeyException e) {}
				return null;
			}
		};
		
		inhibitCheck();
		
		if((!inhibited||!settings.getBoolean("UsageInhibitorOn", true))&&!usr.equals("")&&!intervention.equals("")||settings.getString("interventionMode", "").equals("2")){
			new AsyncLog().execute(this);
			
			NotificationManager notificationManager = (NotificationManager) 
			getBaseContext().getSystemService(getBaseContext().NOTIFICATION_SERVICE);
			Notification notification = new Notification(R.drawable.star,
    		  "A new notification", System.currentTimeMillis());

			// Hide the notification after its selected
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.defaults |= Notification.DEFAULT_SOUND;

			Intent intent = new Intent(getBaseContext(), ViewGoalsActivity.class);
			PendingIntent activity = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);
			notification.setLatestEventInfo(getBaseContext(), "POWeR Tracker Reminder",
				"This is a reminder to take some time to view your goals.", activity);
			notification.number += 1;
			notificationManager.notify(0, notification);
		}
		
		stopSelf();
	    
	}
	
	@Override
    public void onDestroy() {
        super.onDestroy();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    	
	public void inhibitCheck(){
    	
    	//Detect if on inhibited week
		String[] startDateString = settings.getString("appStart", "").split("-");
		Date startDate = new Date(new Integer(startDateString[2]),new Integer(startDateString[1]),new Integer(startDateString[0]));
		currentDate = new Date();
		long diff = currentDate.getTime()-startDate.getTime();
		double daysDiff = diff/(1000*60*60*24);
		day = new Integer(new Double(daysDiff).intValue()+1);
				
		week=new Double(Math.ceil(new Double(day/7.0))).intValue();
		
		
    	inhibited=false;
    	
    	if(!settings.getString("usageInhibitorWeeks", "").equals("")){
    		   		
    		String weeks=settings.getString("usageInhibitorWeeks", "");
    		inhibitedWeeks=weeks.split(",");
    		for(String w:inhibitedWeeks){
    			if(new Integer(w).intValue()==week)
    				inhibited=true;
    			
    		}
    	}
    	
        	
    }
}